<template>
  <div class="min-h-screen bg-gray-50">
    <NavBar />

    <div class="max-w-7xl mx-auto px-4 py-8">
      <!-- 非作者引导面板 -->
      <div v-if="!isAuthor && !isAdmin" class="bg-white rounded-2xl shadow p-10 text-center mb-8">
        <div class="text-2xl font-semibold text-gray-800 mb-2">成为作者，开启创作之旅</div>
        <div class="text-gray-500 mb-6">完成实名认证后即可创建、管理你的作品</div>
        <div class="flex items-center justify-center gap-4">
          <button class="btn-primary" @click="$router.push('/author/register')">实名认证并申请作者</button>
          <button class="px-4 py-2 rounded-lg border" @click="$router.replace('/')">返回首页</button>
        </div>
      </div>

      <!-- 顶部横幅（对标番茄作家中心的门户Banner） -->
      <div v-if="isAuthor || isAdmin" class="relative overflow-hidden rounded-2xl mb-8"
           style="background: radial-gradient(120% 120% at 0% 0%, #ffedd5 0%, #ffd1b2 45%, #ffb199 100%);">
        <div class="px-8 py-10 md:px-12 md:py-14">
          <div class="flex items-center gap-3 text-white/90">
            <span class="text-3xl">🍅</span>
            <span class="text-xl font-semibold tracking-wide">作家中心</span>
            <button v-if="isAdmin" @click="$router.push('/admin')" class="ml-auto px-3 py-1.5 rounded-lg bg-white/90 hover:bg-white text-emerald-700 border border-emerald-200">
              管理员操作
            </button>
          </div>
          <div class="mt-4 text-2xl md:text-3xl font-bold text-white">
            你好，{{ authorName }}，开启你的精品IP创作之旅
          </div>
          <div class="mt-3 text-white/90">创建作品、管理章节、查看数据与收益，一站式创作服务</div>
          <div class="mt-6 flex flex-wrap gap-3">
            <button class="btn-primary" @click="createNovel">立即创建作品</button>
            <button class="px-4 py-2 rounded-lg bg-white/90 hover:bg-white text-orange-600" @click="openDrafts">打开草稿箱</button>
            <button class="px-4 py-2 rounded-lg bg-white/90 hover:bg-white text-gray-700" @click="openAnalytics">查看数据概览</button>
            <button class="px-4 py-2 rounded-lg bg-white/90 hover:bg-white text-indigo-700" @click="$router.push('/author/register')">作者认证</button>
          </div>
        </div>
      </div>

      <!-- 主体两栏布局：仅作者/管理员可见（对标门户信息流） -->
      <div v-if="isAuthor || isAdmin" class="grid grid-cols-1 lg:grid-cols-12 gap-6">
        <!-- 左：主内容 -->
        <div class="lg:col-span-8">
          <!-- 数据概览卡片 -->
          <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
            <div v-for="card in statCards" :key="card.key" class="bg-white rounded-lg shadow p-6">
              <div class="text-gray-500">{{ card.title }}</div>
              <div class="mt-2 text-2xl font-semibold">{{ card.value }}</div>
              <div class="mt-1 text-sm text-gray-400">{{ card.subtitle }}</div>
            </div>
          </div>

          <!-- 我的作品列表（番茄“最近更新”风格的表格） -->
          <div class="bg-white rounded-lg shadow">
            <div class="p-6 border-b border-gray-100 flex items-center justify-between">
              <div class="text-lg font-semibold">我的作品</div>
              <div class="flex gap-2">
                <input v-model="searchKeyword" placeholder="搜索标题…" class="px-3 py-2 border border-gray-300 rounded-lg w-56" />
                <select v-model="filterStatus" class="px-3 py-2 border border-gray-300 rounded-lg">
                  <option value="">全部状态</option>
                  <option :value="1">连载中</option>
                  <option :value="2">已完结</option>
                </select>
                <select v-model="filterAudit" class="px-3 py-2 border border-gray-300 rounded-lg">
                  <option value="">审核状态</option>
                  <option :value="1">待审核</option>
                  <option :value="2">已通过</option>
                  <option :value="3">已拒绝</option>
                </select>
                <button class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50" @click="resetFilters">重置</button>
              </div>
            </div>

            <div class="overflow-x-auto">
              <table class="min-w-full">
                <thead>
                  <tr class="bg-gray-50 text-left text-sm text-gray-500">
                    <th class="px-6 py-3">标题</th>
                    <th class="px-6 py-3">分类</th>
                    <th class="px-6 py-3">状态</th>
                    <th class="px-6 py-3">审核</th>
                    <th class="px-6 py-3">字数</th>
                    <th class="px-6 py-3">阅读</th>
                    <th class="px-6 py-3">收藏</th>
                    <th class="px-6 py-3">操作</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="item in filteredWorks" :key="item.id" class="border-t text-sm">
                    <td class="px-6 py-3 font-medium text-gray-800">{{ item.title }}</td>
                    <td class="px-6 py-3 text-gray-500">{{ item.category_name }}</td>
                    <td class="px-6 py-3">
                      <span :class="badgeClass(item.status)">{{ item.status === 1 ? '连载中' : '已完结' }}</span>
                    </td>
                    <td class="px-6 py-3">
                      <span :class="auditBadgeClass(item.audit_status)">{{ auditText(item.audit_status) }}</span>
                    </td>
                    <td class="px-6 py-3 text-gray-500">{{ item.word_count }}</td>
                    <td class="px-6 py-3 text-gray-500">{{ item.view_count }}</td>
                    <td class="px-6 py-3 text-gray-500">{{ item.collect_count }}</td>
                    <td class="px-6 py-3">
                      <div class="flex gap-2">
                        <button class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50" @click="editWork(item)">编辑</button>
                        <button class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50" @click="manageChapters(item)">章节</button>
                        <button class="px-3 py-1.5 border border-gray-300 rounded hover:bg-gray-50" @click="toggleFeatured(item)">{{ item.is_featured ? '取消推荐' : '推荐' }}</button>
                      </div>
                    </td>
                  </tr>
                  <tr v-if="filteredWorks.length === 0">
                    <td colspan="8" class="px-6 py-10 text-center text-gray-400">暂无作品，点击“立即创建作品”开始创作吧</td>
                  </tr>
                </tbody>
              </table>
            </div>
          </div>
        </div>

        <!-- 右：侧边信息区（作家福利/最新资讯/入口） -->
        <div class="lg:col-span-4 space-y-6">
          <div class="bg-white rounded-lg shadow p-6">
            <div class="text-lg font-semibold mb-3">作家福利</div>
            <ul class="space-y-2 text-sm text-orange-600">
              <li><a class="hover:underline" href="https://fanqienovel.com/" target="_blank">番茄作家福利区</a></li>
              <li><a class="hover:underline" href="https://fanqienovel.com/" target="_blank">版权专区与改编合作</a></li>
              <li><a class="hover:underline" href="https://fanqienovel.com/" target="_blank">作家助手与帮助中心</a></li>
            </ul>
          </div>

          <div class="bg-white rounded-lg shadow p-6">
            <div class="text-lg font-semibold mb-3">最新资讯</div>
            <ul class="space-y-2 text-sm text-gray-600">
              <li v-for="n in news" :key="n.title" class="flex items-start gap-2">
                <span class="mt-1 w-1.5 h-1.5 rounded-full bg-orange-500"></span>
                <a class="hover:text-orange-600" :href="n.url" target="_blank">{{ n.title }}</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import NavBar from '@/components/layout/NavBar.vue'
import { novelAPI, userAPI } from '@/api/novel'

const userInfo = ref(null)
const isAdmin = ref(false)
const isAuthor = computed(() => {
  const role = userInfo.value?.role
  return role === 2 || role === 3
})
onMounted(() => {
  try {
    const raw = localStorage.getItem('user_info')
    userInfo.value = raw ? JSON.parse(raw) : null
  } catch {}
  // 拉取我的作品
  fetchMyWorks()
  // 检测是否管理员，用于显示管理员入口
  ;(async () => {
    try {
      const res = await userAPI.isAdmin()
      isAdmin.value = !!(res?.data?.is_admin)
    } catch (e) {
      isAdmin.value = false
    }
  })()
})

const authorName = computed(() => userInfo.value?.nickname || '作者')
const authorNameFirstLetter = computed(() => (authorName.value?.[0] || '作'))

// 模拟统计卡片
const statCards = ref([
  { key: 'words', title: '总字数', value: '86,210', subtitle: '含草稿与已发布' },
  { key: 'views', title: '总阅读', value: '128,904', subtitle: '近30天 +3.2%' },
  { key: 'collections', title: '总收藏', value: '4,126', subtitle: '近30天 +1.1%' },
])

// 作品列表（从后端获取我的作品）
const works = ref([])

const fetchMyWorks = async () => {
  try {
    const res = await novelAPI.getWriterNovels()
    works.value = res?.data?.list || []
  } catch (e) {
    console.error('获取我的作品失败', e)
    works.value = []
  }
}

// 过滤器
const searchKeyword = ref('')
const filterStatus = ref('')
const filterAudit = ref('')

const filteredWorks = computed(() => {
  return works.value.filter((w) => {
    const byKw = searchKeyword.value ? w.title.includes(searchKeyword.value) : true
    const byStatus = filterStatus.value ? w.status === Number(filterStatus.value) : true
    const byAudit = filterAudit.value ? w.audit_status === Number(filterAudit.value) : true
    return byKw && byStatus && byAudit
  })
})

const resetFilters = () => {
  searchKeyword.value = ''
  filterStatus.value = ''
  filterAudit.value = ''
}

const badgeClass = (status) =>
  status === 1
    ? 'px-2 py-0.5 rounded text-xs bg-green-50 text-green-600'
    : 'px-2 py-0.5 rounded text-xs bg-gray-100 text-gray-600'

const auditText = (s) => (s === 1 ? '待审核' : s === 2 ? '已通过' : '已拒绝')
const auditBadgeClass = (s) =>
  s === 2
    ? 'px-2 py-0.5 rounded text-xs bg-emerald-50 text-emerald-600'
    : s === 1
    ? 'px-2 py-0.5 rounded text-xs bg-amber-50 text-amber-600'
    : 'px-2 py-0.5 rounded text-xs bg-rose-50 text-rose-600'

// 占位交互（后端完成后替换）
const createNovel = () => alert('后端接口未就绪：将打开新建小说对话框')
const openDrafts = () => alert('后端接口未就绪：将打开草稿箱')
const openAnalytics = () => alert('后端接口未就绪：将打开数据概览')
const editWork = (item) => alert(`编辑《${item.title}》：后端接口未就绪`)
const manageChapters = (item) => alert(`章节管理《${item.title}》：后端接口未就绪`)
const toggleFeatured = (item) => (item.is_featured = !item.is_featured)
</script>

<style scoped>
.btn-primary { padding: 0.5rem 1rem; border-radius: 0.5rem; color: #fff; background-color: #f97316; transition: background-color .2s ease; }
.btn-primary:hover { background-color: #ea580c; }
</style>


